package com.xk.meeting.controller;

import com.xk.meeting.entity.User;
import com.xk.meeting.utils.UtilHelper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@WebFilter(urlPatterns = "/*",initParams = {@WebInitParam(name = "url",value = "back,login,captcha,reg.jsp,regUser,index,announceList,applyList,meetingList,apply.jsp,meetinglist,autoLogin,top.jsp,css,fonts,images,js")})
public class LoginFilter implements Filter {
    private List<String> urls;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        request.setCharacterEncoding("utf8");

        String requestURI = request.getRequestURI();

        /* || requestURI.contains("back") || requestURI.contains("login") || requestURI.contains("reg.jsp") || requestURI.contains("regUser") ||
                requestURI.contains("index") || requestURI.contains("announceList") || requestURI.contains("applyList") || requestURI.contains("meetingList") ||
                requestURI.contains("apply.jsp") || requestURI.contains("meetinglist") || requestURI.contains("autoLogin") || requestURI.contains("top.jsp")){*/
            if(requestURI.equals("/meeting/") || UtilHelper.contains(requestURI,urls)){
                chain.doFilter(request, response);
            }else {
                HttpSession session = request.getSession();
                User user = (User)session.getAttribute("user");
                if (user != null){
                    chain.doFilter(request, response);
                }else {
                    response.sendRedirect(request.getContextPath()+"/login.jsp");
                }
            }

    }

    public void init(FilterConfig config) throws ServletException {
        String url = config.getInitParameter("url");
        String[] strs = url.split(",");
        urls = Arrays.asList(strs);

    }

}
